package app.foodnote;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ShowPlacesList extends Activity {
	// Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();
    
    // Google Places
    GooglePlaces googlePlaces;
 
    // Places List
    PlacesList nearPlaces;
 
    // Progress dialog
    ProgressDialog pDialog;
 
    // Places Listview
    ListView lv;
 
    // ListItems data
    ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
 
    // KEY Strings
    public static String KEY_REFERENCE = "reference"; // id of the place
    public static String KEY_NAME = "name"; // name of the place
    public static String KEY_VICINITY = "vicinity"; // Place area name
    
    @Override
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.showplaceslist);
	        
	        lv = (ListView) findViewById(R.id.list);
	        
	        
	        
	       // Toast.makeText(getApplicationContext(), "Da nhan " + LAT_EXTRA + ", " + LOG_EXTRA, Toast.LENGTH_LONG).show();
	        
	       
	        // calling background Async task to load Google Places
	        // After getting places from Google all the data is shown in listview
	        new LoadPlaces().execute();
	        
	        lv.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> paretn, View view,
						int position, long id) {
					// getting values from selected ListItem
					String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
					
					Intent in = new Intent(getApplicationContext(), SinglePlaceActivity.class);
					in.putExtra(KEY_REFERENCE, reference);
					startActivity(in);
					
				}
			});
    }
    public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.menu_show_place_list_and_map, menu);
		//setMenuBackground(); 
		return (super.onCreateOptionsMenu(menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId()==R.id.back){
			startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
			return true;
		}
		return (super.onOptionsItemSelected(item));
		
	}
    
    /**
     * Background Async Task to Load Google places
     * */
    class LoadPlaces extends AsyncTask<String, String, String> {
    	
    	/**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ShowPlacesList.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

		@Override
		protected String doInBackground(String... params) {
			// creating Places class object
            googlePlaces = new GooglePlaces();
 
            try {
                // Separeate your place types by PIPE symbol "|"
                // If you want all types places make it as null
                // Check list of types supported by google
                String types = "cafe|food|restaurant"; // Listing places only cafes, restaurants, foods restaurant|
 
                // Radius in meters - increase this value if you don't find any places
                double radius = 1000; // 1000 meters 
 
                double LAT_EXTRA = getIntent().getExtras().getDouble("GOOGLE_API_LAT_EXTRA");
    	        double LOG_EXTRA = getIntent().getExtras().getDouble("GOOGLE_API_LOG_EXTRA");
    	        
                // get nearest places
                nearPlaces = googlePlaces.search(LAT_EXTRA, LOG_EXTRA, radius, types);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
		}
    	
		/**
	     * After completing background task Dismiss the progress dialog
	     * and show the data in UI
	     * Always use runOnUiThread(new Runnable()) to update UI from background
	     * thread, otherwise you will get error
	     * **/
	    protected void onPostExecute(String file_url) {
	        // dismiss the dialog after getting all products
	        pDialog.dismiss();
	        // updating UI from Background Thread
	        runOnUiThread(new Runnable() {
	            public void run() {
	                /**
	                 * Updating parsed Places into LISTVIEW
	                 * */
	                // Get json response status
	                String status = nearPlaces.status;

	                // Check for all possible status
	                if(status.equals("OK")){
	  
	                    // Successfully got places details
	                    if (nearPlaces.results != null) {
	                        // loop through each place
	                        for (Place p : nearPlaces.results) {
	                            HashMap<String, String> map = new HashMap<String, String>();

	                            // Place reference won't display in listview - it will be hidden
	                            // Place reference is used to get "place full details"
	                            map.put(KEY_REFERENCE, p.reference);

	                            // Place name
	                            map.put(KEY_NAME, p.name);

	                            // adding HashMap to ArrayList
	                            placesListItems.add(map);
	                        }
	                        // list adapter
	                        ListAdapter adapter = new SimpleAdapter(ShowPlacesList.this, placesListItems,
	                                R.layout.list_item,
	                                new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
	                                        R.id.reference, R.id.name });

	                        // Adding data into listview
	                        lv.setAdapter(adapter);
	                    }
	                }
	                else if(status.equals("ZERO_RESULTS")){
	                    // Zero results found
	                    alert.showAlertDialog(ShowPlacesList.this, "Địa Điểm Xung Quanh",
	                            "Không có nơi nào được tìm thấy.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	                else if(status.equals("UNKNOWN_ERROR"))
	                {
	                    alert.showAlertDialog(ShowPlacesList.this, "Lỗi",
	                            "Không biết lỗi xảy ra.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	                else if(status.equals("OVER_QUERY_LIMIT"))
	                {
	                    alert.showAlertDialog(ShowPlacesList.this, "Lỗi",
	                            "Truy vấn tới Google Place bị giới hạn.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	                else if(status.equals("REQUEST_DENIED"))
	                {
	                    alert.showAlertDialog(ShowPlacesList.this, "Lỗi",
	                            "Yêu cầu bị từ chối.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	                else if(status.equals("INVALID_REQUEST"))
	                {
	                    alert.showAlertDialog(ShowPlacesList.this, "Lỗi",
	                            "Yêu cầu không hợp lệ.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	                else
	                {
	                    alert.showAlertDialog(ShowPlacesList.this, "Lỗi",
	                            "Xin lỗi đã xảy ra lỗi.",
	                            false);
	                    startActivity(new Intent(ShowPlacesList.this, FoodPlaces.class));
	                }
	            }
	        });

	    }
    }
    
}
